package com.denlaku.longan.filter;

import com.denlaku.longan.Const;
import com.denlaku.longan.core.HttpSessionManager;
import com.denlaku.longan.vo.User;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;

import java.io.IOException;

/**
 * @author tianx
 */
public class SecurityFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        Object userInfo = session.getAttribute(Const.KEY_USER_INFO);
        if (!(userInfo instanceof User user)) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        HttpSessionManager.putSession(user.getId(), session);
        super.doFilter(request, response, chain);
    }
}
